import 'package:flutter/material.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:fsharing/core/models/withdraw.dart';
import 'package:fsharing/core/services/api.dart';
import 'package:fsharing/core/viewmodels/pages/mine/manage/withdraw_apply_model.dart';
import 'package:fsharing/core/viewmodels/pages/mine/manage/withdraw_cancel_model.dart';
import 'package:fsharing/core/viewmodels/pages/mine/manage/withdraw_delete_model.dart';
import 'package:fsharing/core/viewmodels/pages/mine/manage/withdraw_query_model.dart';
import 'package:fsharing/core/viewmodels/view_model.dart';
import 'package:fsharing/main.dart';
import 'package:fsharing/ui/widgets/background_container.dart';
import 'package:fsharing/ui/widgets/round_back_button.dart';
import 'package:oktoast/oktoast.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class WithdrawPage extends StatelessWidget {
  final int storeId;

  WithdrawPage({
    Key key,
    @required this.storeId,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    Api api = Provider.of(context, listen: false);
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (context) => WithdrawQueryModel(api, storeId)),
        ChangeNotifierProvider(create: (context) => WithdrawApplyModel(api)),
        ChangeNotifierProvider(create: (context) => WithdrawCancelModel(api)),
        ChangeNotifierProvider(create: (context) => WithdrawDeleteModel(api))
      ],
      child: BackgroundContainer(
        child: Scaffold(
          appBar: AppBar(
            leading: RoundBackButton(),
            title: Text('提现申请'),
          ),
          body: Consumer<WithdrawQueryModel>(
            builder: (context, model, child) {
              switch (model.viewState) {
                case ViewState.busy:
                  return Center(
                    child: CircularProgressIndicator(),
                  );
                case ViewState.error:
                  return Center(
                    child: Text(model.errorMessage),
                  );
                case ViewState.success:
                  return Column(
                    children: <Widget>[
                      Expanded(
                        child: _ListWidget(
                          list: model.list,
                          withdrawList: model.withdrawList,
                        ),
                      ),
                      _BottomWidget(),
                    ],
                  );
                default:
                  return Container();
              }
            },
          ),
        ),
      ),
    );
  }
}

class _ListWidget extends StatelessWidget {
  final RefreshController _refreshController = RefreshController();
  final List<Withdraw> list;
  final List<Withdraw> withdrawList;

  _ListWidget({
    Key key,
    @required this.list,
    @required this.withdrawList,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return SmartRefresher(
      controller: _refreshController,
      child: ListView.separated(
        padding: EdgeInsets.symmetric(horizontal: 12),
        itemBuilder: (context, index) {
          return Container(
            child: _ListItemWidget(withdraw: list[index]),
          );
        },
        separatorBuilder: (context, index) {
          return Divider(
            height: 12,
            color: Colors.transparent,
          );
        },
        itemCount: list.length,
      ),
      enablePullDown: false,
      enablePullUp: withdrawList.length == 10,
      onLoading: () => _onLoadData(context),
    );
  }

  void _onLoadData(BuildContext context) async {
    WithdrawQueryModel model = Provider.of(context, listen: false);
    await model.loadData();
    _refreshController.loadComplete();
  }
}

class _ListItemWidget extends StatelessWidget {
  final Withdraw withdraw;

  const _ListItemWidget({
    Key key,
    @required this.withdraw,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Slidable(
      child: Stack(
        alignment: Alignment.centerRight,
        children: <Widget>[
          Column(
            children: <Widget>[
              _ListItemHeaderWidget(withdraw: withdraw),
              _ListItemFooterWidget(withdraw: withdraw),
            ],
          ),
          if (withdraw.auditStatus == Withdraw.AUDITING)
            Image.asset('assets/images/withdraw/img_auditing.png', width: 96),
        ],
      ),
      actionPane: SlidableDrawerActionPane(),
      secondaryActions: <Widget>[
        if (withdraw.auditStatus == Withdraw.NOT_APPLY)
          IconSlideAction(
            icon: Icons.check,
            caption: '申请审核',
            color: Colors.green,
            onTap: () => _onApplyClicked(context),
          ),
        if (withdraw.auditStatus == Withdraw.AUDITING)
          IconSlideAction(
            icon: Icons.clear,
            caption: '撤回',
            color: Colors.red,
            onTap: () => _onCancelClicked(context),
          ),
        if (withdraw.auditStatus == Withdraw.NOT_APPLY ||
            withdraw.auditStatus == Withdraw.AUDIT_FAIL)
          IconSlideAction(
            icon: Icons.clear,
            caption: '删除',
            color: Colors.red,
            onTap: () => _onDeleteClicked(context),
          ),
      ],
    );
  }

  /// 申请
  void _onApplyClicked(BuildContext context) async {
    WithdrawApplyModel withdrawApplyModel = Provider.of(context, listen: false);
    ViewState viewState = await withdrawApplyModel.withdrawApply(withdraw);
    switch (viewState) {
      case ViewState.error:
        showToast(withdrawApplyModel.errorMessage);
        break;
      default:
        WithdrawQueryModel withdrawQueryModel = Provider.of(context, listen: false);
        withdrawQueryModel.refreshData();
        break;
    }
  }

  /// 撤回
  void _onCancelClicked(BuildContext context) async {
    WithdrawCancelModel withdrawCancelModel = Provider.of(context, listen: false);
    ViewState viewState = await withdrawCancelModel.withdrawCancel(withdraw);
    switch (viewState) {
      case ViewState.error:
        showToast(withdrawCancelModel.errorMessage);
        break;
      default:
        WithdrawQueryModel withdrawQueryModel = Provider.of(context, listen: false);
        withdrawQueryModel.refreshData();
        break;
    }
  }

  /// 删除
  void _onDeleteClicked(BuildContext context) async {
    WithdrawDeleteModel withdrawDeleteModel = Provider.of(context, listen: false);
    ViewState viewState = await withdrawDeleteModel.withdrawDelete(withdraw);
    switch (viewState) {
      case ViewState.error:
        showToast(withdrawDeleteModel.errorMessage);
        break;
      default:
        WithdrawQueryModel withdrawQueryModel = Provider.of(context, listen: false);
        withdrawQueryModel.refreshData();
        break;
    }
  }
}

class _ListItemHeaderWidget extends StatelessWidget {
  final Withdraw withdraw;

  const _ListItemHeaderWidget({
    Key key,
    @required this.withdraw,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 12),
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage('assets/images/cart/img_store.png'),
          fit: BoxFit.fill,
        ),
      ),
      height: 45,
      child: Row(
        children: <Widget>[
          Image.asset('assets/images/bank/ic_bank.png', width: 21),
          SizedBox(width: 8),
          Expanded(
            child: Text.rich(
              TextSpan(
                text: '入账账号',
                style: TextStyle(fontSize: 17),
                children: [
                  TextSpan(
                    text: '  (${withdraw.bankCardId})',
                    style: TextStyle(fontSize: 12),
                  ),
                ],
              ),
            ),
          ),
          Text(withdraw.cardOwnerName, style: TextStyle(fontSize: 17)),
        ],
      ),
    );
  }
}

class _ListItemFooterWidget extends StatelessWidget {
  final Withdraw withdraw;

  const _ListItemFooterWidget({
    Key key,
    @required this.withdraw,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Theme(
      data: lightTheme(),
      child: Material(
        borderRadius: BorderRadius.vertical(
          bottom: Radius.circular(8),
        ),
        child: Container(
          padding: EdgeInsets.all(12),
          child: Column(
            children: <Widget>[
              Row(
                children: <Widget>[
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Text('服务类型：${withdraw.accountTypeName}'),
                        SizedBox(height: 4),
                        Text('服务费用：${withdraw.serviceFee}'),
                        if (withdraw.auditStatus == Withdraw.AUDIT_FAIL) ...[
                          SizedBox(height: 4),
                          Text('审核备注：${withdraw.auditNote}'),
                        ]
                      ],
                    ),
                  ),
                  Text(
                    '+${withdraw.amount}',
                    style: TextStyle(color: Theme.of(context).accentColor, fontSize: 19),
                  ),
                  if (withdraw.auditStatus == Withdraw.AUDIT_FAIL)
                    Container(
                      margin: EdgeInsets.only(left: 6),
                      child: Image.asset('assets/images/withdraw/img_audit_fail.png', width: 24),
                    ),
                  if (withdraw.auditStatus == Withdraw.AUDIT_SUCCESS)
                    Container(
                      margin: EdgeInsets.only(left: 6),
                      child: Image.asset('assets/images/withdraw/img_audit_success.png', width: 24),
                    ),
                ],
              ),
              SizedBox(height: 8),
              Divider(height: 1),
              SizedBox(height: 8),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  Text(
                    '申请时间：${withdraw.createTime}',
                    style: TextStyle(color: Colors.grey, fontSize: 10),
                  ),
                  Text(
                    '转款时间：${withdraw.withdrawTime.isNotEmpty ? withdraw.withdrawTime : '--:--:--'}',
                    style: TextStyle(color: Colors.grey, fontSize: 10),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class _BottomWidget extends StatelessWidget {
  const _BottomWidget({
    Key key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      child: Container(
        alignment: Alignment.center,
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/withdraw/img_button.png'),
            fit: BoxFit.fill,
          ),
        ),
        height: 43,
        margin: EdgeInsets.symmetric(vertical: 13, horizontal: 16),
        child: Text(
          '创建店铺提现',
          style: TextStyle(fontSize: 19),
        ),
      ),
      onTap: () => _onEditClicked(context),
    );
  }

  void _onEditClicked(BuildContext context) async {
    var result = await Navigator.of(context).pushNamed('/withdraw/edit');
    if (result is bool ? result : false) {
      WithdrawQueryModel model = Provider.of(context, listen: false);
      model.refreshData();
    }
  }
}
